﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.NetworkInformation;
using System.Security.Cryptography;

namespace p2p.Misc.HashGenerator
{
    public class Hash
    {
        private string hash;

        // this should allow a this means that the same computer can make a hash and it not interfer with
        // another hash created on the same computer
        private string GetTimeCode(DateTime value)
        {
            // returns the a string of the current date fail safe this is unique
            return value.ToString("yyyyMMddHHmmssffff");
        }

        // this will lock the task to computer there current on
        private string GetMacAddress()
        {
            // gets the first mac address on the computer as this should be unique
            string macAddr =
            (
                from nic in NetworkInterface.GetAllNetworkInterfaces()
                where nic.OperationalStatus == OperationalStatus.Up
                select nic.GetPhysicalAddress().ToString()
            ).FirstOrDefault();
            return macAddr;
        }
        // instanciate the SHA1 C# CryptoService
        private SHA1CryptoServiceProvider cryptoTransformSHA1 = new SHA1CryptoServiceProvider();

        // use the timeCode and the MacAddress then SHA1 and Base64 encode to make sure that
        // the hash code given is never able to be obtained again
        public string getHash()
        {
            // get the above generations and apppend the time code with a salt and then append the mac address
            // then convert them to a byte array
            byte[] buffer = Encoding.ASCII.GetBytes(GetTimeCode(DateTime.Now) + "p2psaltgoeshere" + GetMacAddress());
            
            // pass the byte array into the SHA1 c# Crypto Service removing hypens and convert the returning
            // byte array into a string
            hash = BitConverter.ToString(
                cryptoTransformSHA1.ComputeHash(buffer)).Replace("-", "");

            // just to make sure its even harder to understand it pass it to the base64 dll encoder then return it
            return Base64.Base64.Encode(hash);
        }
    }
}
